# -*- coding: utf-8 -*-
"""
Created on Tue Apr  4 14:31:42 2017

@author: glacity@126.com
"""

import os
import time
import re
import requests
from bs4 import BeautifulSoup
from http import cookiejar

headers = {
    "Host": "192.168.2.78:8012",
    "Referer": "http://192.168.2.78:8012/Portal/LoginBegin.aspx",
    "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0"
}

# 使用登录cookie信息
print("使用登录cookie信息")
session = requests.session()
session.cookies = cookiejar.LWPCookieJar(filename='cookies.txt')
try:
    print(session.cookies)
    session.cookies.load(ignore_discard=True)

except:
    print("还没有cookie信息")


def changeName(name):
    print("文件改名程序")
    a = os.path.splitext(name)#Split函数将扩展命分割开.
    #p0 = r"NNN"
    #pattern0 = re.compile(p0)#我们在编译这段正则表达式
    #matcher0 = re.match(pattern0,a[0])#在源文本中搜索符合正则表达式的部分
    #if a[1] == '.zip' and matcher0 != 'None' : 
    #print("是不是文件夹:",os.path.isdir(name)) #打印出来
    
    p2 = r"(\d\d\d\d\d\d[A-Z]\d\d\-\S+)"
    pattern2 = re.compile(p2)#我们在编译这段正则表达式
    matcher2 = re.search(pattern2,a[0])#在源文本中搜索符合正则表达式的部分
    #print("是否匹配成功:",matcher2) 
    if matcher2 != None and os.path.isdir(name) == 0:
        NewName=matcher2.group(1)+a[1]
        NewPath=matcher2.group(1)[:9]

    return [NewPath,NewName]

def login(userName, Password):
    login_url = "http://192.168.2.78:8012/Portal/LoginBegin.aspx"
    print("登录地址为：",login_url)
    data = {
        'Todo': "Validate",
        'LoginName': userName,
        'Password': Password,        
        'CDomain': "Local",
        'FromUrl': "1",
        'Server': "Base"}
    print("登录数据为：",data)  
    try:
        response = session.post(login_url, data=data, headers=headers)
        login_code = response.json()
    except:
        print("错误")  
    print(login_code['Desc'])
    for i in session.cookies:
        print(i)
    session.cookies.save()

def getDrawing():
    print('开始下载图纸')
    root=r'G:\图纸\test'
    url=r'http://192.168.2.77:8008/Download.aspx?FileId='
    Num=459968#表示网页开始的数字
    while Num<459980:
        time.sleep(5)
        try:
            if not os.path.exists(root):
                os.mkdir(root)
                #判断根目录是否存在，os.madir()创建根目录
                
            Num=Num+1
                
            url1=url+str(Num).zfill(6)
            print('网络图纸地址：',url1)
            r=requests.get(url1)
            print('状态：',r.status_code)
            getName=r.headers['Content-Disposition'][21:-1]
            
            newName=changeName(getName)[1]
            newPath=root+os.sep+changeName(getName)[0]
            if not os.path.exists(newPath):
                os.mkdir(newPath)
            print('图纸名称：',newName)
                       
            print('保存地址：',newPath)
            with open(newPath+os.sep+newName,'wb')as f:
                    #wb存为二进制文件
                f.write(r.content)
                #   将返回内容写入文件 r.content返回二进制形式
                f.close()
                print('保存成功')
            
        except:
            print('爬取失败')


if __name__ == '__main__':
    userName = "guobing"
    Password = "66776"
    login(userName, Password)
    getDrawing()



